package cn.com.ccxe.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EncodingFilter implements Filter {

	private static final Logger 	logger = LoggerFactory.getLogger(EncodingFilter.class);
	/**
	 * 默认的字符编码。
	 */
	protected String 				encoding = null;
	/**
	 * 过滤器配置对象。
	 */
	protected FilterConfig 			filterConfig = null;
	/**
	 * 是否使用编码过滤器。
	 */
	protected boolean 				isIgnore = true;

	public void destroy() {
		this.encoding = null;
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 有条件地设置字符编码使用
		if (isIgnore || (request.getCharacterEncoding() == null)) {
			String encoding = this.encoding;
			if (encoding != null)
				logger.debug("使用的字符编码为：{}",encoding);
				request.setCharacterEncoding(encoding);
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		
		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		String value = filterConfig.getInitParameter("isIgnore");
		if (value == null)
			this.isIgnore = true;
		else if (value.equalsIgnoreCase("true"))
			this.isIgnore = true;
		else if (value.equalsIgnoreCase("yes"))
			this.isIgnore = true;
		else
			this.isIgnore = false;
	}
}
